//
//  ZYAudioManager.m
//  HB
//
//  Created by 孙智慧 on 16/1/22.
//  Copyright © 2016年 孙智慧. All rights reserved.
//

#import "ZYAudioManager.h"

@implementation ZYAudioManager

//设置后台播放
+(void) initAvAduioSesson
{
    // 音频会话
    AVAudioSession *session = [AVAudioSession sharedInstance];
    
    // 设置会话类型（播放类型、播放模式,会自动停止其他音乐的播放）
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    // 激活会话
    [session setActive:YES error:nil];
    
}

-(NSURL *) downLoadMp3:(NSString *)urlStr andMp3Name:(NSString *)mp3Name
{
    NSString * filePath=[FxGlobal getCacheMp3];
    if (![Common checkMp3Exist:mp3Name])
    {
        
        NSURL * url=[[NSURL alloc] initWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        
        NSData * audioData = [NSData dataWithContentsOfURL:url];
        
        //将数据保存到本地指定位置
        [audioData writeToFile:filePath atomically:YES];
    }
    //播放本地音乐
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    return fileURL;
}


//播放音乐
- (AVAudioPlayer *)playingMusic:(NSString *)filename andFilePath:(NSString *)filePath
{
    if (filename == nil || filename.length == 0)  return nil;
    
    AVAudioPlayer *player = self.musicPlayers[filename];      //先查询对象是否缓存了
    
    if (!player)
    {
        NSURL *url= [self downLoadMp3:filePath andMp3Name:filename];
        
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        
        if (![player prepareToPlay]) return nil;
        
        self.musicPlayers[filename] = player;
        //对象是最新创建的，那么对它进行一次缓存
    }
    
    if (![player isPlaying])
    {
        //如果没有正在播放，那么开始播放，如果正在播放，那么不需要改变什么
        [player play];
    }
    return player;
}

- (void)pauseMusic:(NSString *)filename
{
    if (filename == nil || filename.length == 0)  return;
    
    AVAudioPlayer *player = self.musicPlayers[filename];
    
    if ([player isPlaying])
    {
        [player pause];
    }
}

- (void)stopMusic:(NSString *)filename
{
    if (filename == nil || filename.length == 0)  return;
    
    AVAudioPlayer *player = self.musicPlayers[filename];
    
    [player stop];
    
    [self.musicPlayers removeObjectForKey:filename];
}
@end
